<?php
namespace App\Models\ExpModels;
use App\Models\ParentModel;
use DB;
use App\Components\Tools;
use App\Components\DyToools;
class Exp extends ParentModel{
	/**
     * 与模型关联的数据表。
     *
     * @var string
     */
    protected $table = 'pt_partner';
	
    /**
     * DB::直接操作的数据库表名
     * @var string
     */
    protected $db_table = 'pt_partner';
	
    /**
     * 主键 默认id。
     *
     * @var string
     */
    protected $primaryKey = 'id';
	
    /**
     * 指定是否模型应该被戳记时间。
     *
     * @var bool
     */
    public $timestamps = false;
	
	//根据活动id查询会员id 或者指定的字段值
	function selPid($kid,$fields=''){
		if($fields){
		    // $sql=" select {$fields} from pt_exp_activity where id=? and status=1";
		    // print_r($sql);exit();
			$re=DB::select("select {$fields} from pt_exp_activity where id=? and status=1 and isCheck=1",[$kid]);
			return !empty($re[0]) ? $re[0] : false;
		}
		// else{
			// $re=DB::select("select parnterId from pt_exp_activity where id=? and status=1",[$kid]);
			// return isset($re[0]['parnterId']) ? $re[0]['parnterId'] : 0;
		// }
	}
	
    //查询指定 open_id 的视频数据集
    function findVideo($open_id){
        $sql="select item_id from pt_exp_dyv where open_id = ? and (status=1 or status=0)";
        $re=DB::select($sql,[$open_id]);
        return (isset($re[0]) ? $re : false);
    }
	
    //需要查询的视频的数据
    function selectUser(){
        $sql = "select a.open_id from pt_exp_dyv as a left join pt_exp_activity as b on a.expId=b.id  where b.status=?";
        $data=date('Y-m-d',time());
        $sql.=" and b.endTime > $data ";
        $re = DB::select($sql, [1]);
       return isset($re[0]) ? $re : false;
    }
	
	//保存活动用户信息
	function saveUserInfo($arr,$open_id,$parnterId,$expid){
		$e_account_role="普通用户";$gender='未知';
		if(isset($arr['e_account_role']) && $arr['e_account_role']=='EAccountM'){
			$e_account_role="普通企业号";
		}elseif(isset($arr['e_account_role']) && $arr['e_account_role']=='EAccountS'){
			$e_account_role="认证企业号";
		}elseif(isset($arr['e_account_role']) && $arr['e_account_role']=='EAccountK'){
			$e_account_role="品牌企业号";
		}
		if(isset($arr['gender']) && $arr['gender']==1){
			$gender="男";
		}elseif(isset($arr['gender']) && $arr['gender']==2){
			$gender="女";
		}
		$DyToools=new DyToools();
		$mobileTest=isset($arr['encrypt_mobile']) ? $arr['encrypt_mobile'] : '';
		$mobile=$DyToools->decrypt($mobileTest);
		$data=[
			'province'=>isset($arr['province']) ? $arr['province'] : '',
			'union_id'=>isset($arr['union_id']) ? $arr['union_id'] : '',
			'mobile'=>$mobile ? $mobile : '',
			'avatar'=>isset($arr['avatar']) ? $arr['avatar'] : '',
			'e_account_role'=>$e_account_role,
			'error_code'=>isset($arr['error_code']) ? $arr['error_code'] : '',
			'nickname'=>isset($arr['nickname']) ? htmlspecialchars($arr['nickname'],ENT_QUOTES) : '',
			'city'=>isset($arr['city']) ? $arr['city'] : '',
			'country'=>isset($arr['country']) ? $arr['country'] : '',
			'description'=>isset($arr['description']) ? $arr['description'] : '',
			'gender'=>$gender,
			'update_time'=>date('Y-m-d H:i:s',time()),
            'status'=>1,
            'expId'=>$expid,
		];
		$re=DB::select("select id from pt_exp_user where open_id=? and expId=$expid and parnterId={$parnterId}",[$open_id]);
		$re=isset($re[0]['id']) ? $re[0]['id'] : false;
		if($re){
			return DB::table('pt_exp_user')->where('id',$re)->update($data);
		}else{
			$data['parnterId']=$parnterId;
			$data['open_id']=$open_id;
			$data['create_time']=date('Y-m-d H:i:s',time());
			return DB::table('pt_exp_user')->insertGetId($data);
		}
	}
	
	//领取卡券时判断活动是否开启，卡券是否在时间内
	function checkAct($expId){
		$sql="select a.id,a.status,a.staTime,a.endTime,b.staTime as bstime,b.endTime as betime,b.num,b.status as bstatus from pt_exp_activity as a";
		$sql.=" left join pt_exp_card as b on b.id=a.cardId where a.id=?";
		$re=DB::select($sql,[$expId]);
		$re=isset($re[0]['id']) ? $re[0] : false;
		
		$num=DB::select("select count(id) as num from pt_exp_ucard where expId=?",[$expId]);
		$num=isset($num[0]['num']) ? $num[0]['num'] : 0;
		
		if( $re && $re['status']!=1 ){
			return '活动暂未开启';
		}elseif( $re && $re['staTime']>date('Y-m-d H:i:s') ){
			return '活动未开始';
		}elseif( $re && $re['endTime']<date('Y-m-d H:i:s') ){
			return '活动已结束';
		}elseif($re && $re['bstatus']!=1){
			return '卡券不在活动范围内';
		}elseif( $re && ($re['bstime']>date('Y-m-d H:i:s') || $re['betime']<date('Y-m-d H:i:s')) ){
			return '卡券不在领取时间内';
		}elseif($re && $re['num']>0 && $num>=$re['num']){
			return '你来晚了，卡券已被领完';
		}elseif($re){
			return 1;
		}
		return false;
	}
	
	//获取卡卷数据
    function getCarddata($kid){
	    $result=DB::select("select * from pt_exp_card where id=$kid and   status=1");
		if(isset($result[0]['id'])){
			return $result;
		}
    }
	//领取卡券存库
	function saveUcard($data,$open_id,$expId,$cardId){

		$re=DB::select("select id from pt_exp_ucard where open_id=? and expId={$expId} and cardId={$cardId}",[$open_id]);
		$re=isset($re[0]['id']) ? true :false;
		if($re){
			return -99;
		}else{
			$data['open_id']=$open_id;
			$data['expId']=$expId;
			$data['cardId']=$cardId;
			return DB::table('pt_exp_ucard')->insertGetId($data);
		}
	}
	
	//查询视频
	function selActivity($videoId){
		$re=DB::select("select img,url from pt_exp_videos where status=1 and id=?",[$videoId]);
		return isset($re[0]['url']) ? $re[0] : false;
	}
	
	//视频入库
	function saveDyVideo($data){
		return DB::table('pt_exp_dyv')->insertGetId($data);
	}
	//查询商家昵称
	function selName($open_id){
		$re=DB::select("select nickname from pt_user where open_id=?",[$open_id]);
		return isset($re[0]['nickname']) ? $re[0]['nickname'] : '';
	}
//---------------------------------------------------会员的同城托客活动相关方法--------------------------------------------

    //查询指定活动状态
    function selStatus($kid,$partner_id){
        $re=DB::select("select status from pt_exp_activity where id={$kid} and parnterId=?",[$partner_id]);
        return isset($re[0]['status']) ? $re[0]['status'] : -1;
    }

    //修改活动状态
    function upStatus($kid,$data){
        return DB::table('pt_exp_activity')->where('id',$kid)->update($data);
    }

    //删除活动
    function del($kid){
        return DB::table("pt_exp_activity")->where('id',$kid)->update(['status'=>-1]);
    }

    //拉取商户列表
    function selUsers($partner_id,$thisOpenId,$page=1,$userSreach){
        $size = 20;
        $offset = $size * ($page - 1);
        $countSql="select count(a.id) as count from pt_user as a left join pt_dy_access_token as b on b.open_id=a.open_id where a.partner_id=? and a.status=1 and b.status=1";
        $sql="select a.open_id,a.nickname from pt_user as a left join pt_dy_access_token as b on b.open_id=a.open_id where a.partner_id=?  and a.status=1 and b.status=1";
        if($userSreach!=''){
            $countSql.=" and a.nickname like '%{$userSreach}%'";
            $sql.=" and a.nickname like '%{$userSreach}%'";
        }
        $sql.=" limit {$offset},{$size}";
        // print_r($sql);exit();
        $re=DB::select($sql,[$partner_id]);
        $re=isset($re[0]['open_id']) ? $re : false;
        $count=DB::select($countSql,[$partner_id]);
        $count=isset($count[0]['count']) ? $count[0]['count'] : 0;
      //print_r($sql);exit();
        $html="";
        $nextPage=$page < ceil($count/$size) ? $page+1 : 0;
        if($re){
            if($page==1){
                $html.="<tr onclick=\"javascript:$(this).find('input').prop('checked',true);\">";
                $html.="<td style=\"width:50px;\"><input type=\"radio\" ".(!$thisOpenId ? 'checked' : '')." name=\"openId\" value=\"\" data-name=\"\"></td>";
                $html.="<td>不选择</td>";
                $html.="</tr>";
            }
            foreach($re as $k=>$v){
                $isChecked=$thisOpenId==$v['open_id'] ? 'checked' : '';
                $html.="<tr onclick=\"javascript:$(this).find('input').prop('checked',true);\">";
                $html.="<td><input type=\"radio\" {$isChecked} name=\"openId\" value=\"{$v['open_id']}\" data-name=\"{$v['nickname']}\"></td>";
                $html.="<td>{$v['nickname']}</td>";
                $html.="</tr>";
            }
        }else{
            $html="<tr><td colspan=\"10\">无数据</td></tr>";
        }
        return json_encode(["code"=>0,"msg"=>$html,"nextPage"=>$nextPage]);
    }

    //拉取视频列表
    function selVideos($partner_id,$videoId,$page,$videoSreach){
        $qnUrl=Tools::getOneconfig("/config/third.json",array('qiniu','qnUrl'));
        $size = 20;
        $offset = $size * ($page - 1);
        $countSql="select count(id) as count from pt_exp_videos where status=? and parnterId={$partner_id}";
        $sql="select id,title,url from pt_exp_videos where status=? and parnterId={$partner_id}";
        if($videoSreach!=''){
            $countSql.=" and title like '%{$videoSreach}%'";
            $sql.=" and title like '%{$videoSreach}%'";
        }
        $sql.=" limit {$offset},{$size}";
        $re=DB::select($sql,[1]);
        $re=isset($re[0]['id']) ? $re : false;
        $count=DB::select($countSql,[1]);
        $count=isset($count[0]['count']) ? $count[0]['count'] : 0;

        $html="";
        $nextPage=$page < ceil($count/$size) ? $page+1 : 0;
        if($re){
            foreach($re as $k=>$v){
                $active=$videoId==$v['id'] ? ' active' : '';
                $html.="<div class=\"video{$active}\" data-videoId=\"{$v['id']}\" onmouseover=\"onVideo(this)\" onmouseout=\"outVideo(this)\" onclick=\"dVideo(this)\" >";
                $html.="<video controls src=\"{$qnUrl}/{$v['url']}\" ></video>";
                $html.="<br/><span>{$v['title']}</span>";
                $html.="</div>";
            }
        }else{
            $html="无数据";
        }
        return json_encode(["code"=>0,"msg"=>$html,"nextPage"=>$nextPage]);
    }

    //拉取卡券列表
    function selCards($partner_id,$cardId,$page,$cardSreach){
        $qnUrl=Tools::getOneconfig("/config/third.json",array('qiniu','qnUrl'));
        $size = 20;
        $offset = $size * ($page - 1);
        $countSql="select count(id) as count from pt_exp_card where status=? and parnterId={$partner_id}";
        $sql="select id,title,url from pt_exp_card where status=? and parnterId={$partner_id}";
        if($cardSreach!=''){
            $countSql.=" and title like '%{$cardSreach}%'";
            $sql.=" and title like '%{$cardSreach}%'";
        }
        $sql.=" limit {$offset},{$size}";
        $re=DB::select($sql,[1]);
        $re=isset($re[0]['id']) ? $re : false;
        $count=DB::select($countSql,[1]);
        $count=isset($count[0]['count']) ? $count[0]['count'] : 0;

        $html="";
        $nextPage=$page < ceil($count/$size) ? $page+1 : 0;
        if($re){
            $active=$cardId ? '' : ' active';
            if($page==1){
                $html.="<div class=\"card{$active}\" data-cardId=\"\" onmouseover=\"onCard(this)\" onmouseout=\"outCard(this)\" onclick=\"dCard(this)\">";
                $html.="<img src=\"/img/no-card.png\">";
                $html.="<br/><span>无卡券模式</span>";
                $html.="</div>";
            }
            foreach($re as $k=>$v){
                $active=$cardId==$v['id'] ? ' active' : '';
                $html.="<div class=\"card{$active}\" data-cardId=\"{$v['id']}\" onmouseover=\"onCard(this)\" onmouseout=\"outCard(this)\" onclick=\"dCard(this)\">";
                $html.="<img src=\"{$qnUrl}/{$v['url']}\">";
                $html.="<br/><span>{$v['title']}</span>";
                $html.="</div>";
            }
        }else{
            $html="无数据";
        }
        return json_encode(["code"=>0,"msg"=>$html,"nextPage"=>$nextPage]);
    }

    //添加修改活动
    function saveCaty($kid,$data){
        if(!$kid){
            $data['createTime']=date('Y-m-d');
            return DB::table('pt_exp_activity')->insertGetId($data);
        }else{
            return DB::table('pt_exp_activity')->where('id',$kid)->update($data);
        }
    }
    //添加修改活动

}